package com.mald.plugin.http.client;

import com.mald.plugin.util.HttpClientUtil;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

/**
 * http连接池
 * 请针对某一服务单例使用
 *
 * @author
 * @since 2018/3/1
 */
public class HttpConnectionPool extends HttpClientUtil {

    private CloseableHttpClient httpClient;


    /**
     * init
     *
     * @param maxTotal 最大连接数
     */
    public HttpConnectionPool(int maxTotal) {
        ConnectionSocketFactory plainConnection = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslConnection = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", plainConnection)
                .register("https", sslConnection)
                .build();
        PoolingHttpClientConnectionManager poolManager =
                new PoolingHttpClientConnectionManager(registry);
        //代表连接池中的最大数
        poolManager.setMaxTotal(maxTotal);
        //每个路由的最大连接数，也可以根据HttpHost，设施某个地址的最大连接数
        poolManager.setDefaultMaxPerRoute(maxTotal);
        this.httpClient = HttpClients.custom().setConnectionManager(poolManager).build();
    }


    @Override
    public CloseableHttpClient getHttpClient() {
        return httpClient;
    }

    @Override
    public void releaseConnection(CloseableHttpClient httpClient) {
        //无需关闭httpClient
    }
}
